<script lang="ts" setup>
import type { RoleApi } from '#/api/system/role';
import type { SystemApi } from '#/api/system/system';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { createRole, getRole, updateRole } from '#/api/system/role';
import { getSystemList } from '#/api/system/system';

import { useRoleFormSchema } from '../data';

const emit = defineEmits(['success']);

// 系统列表
const systemList = ref<SystemApi.System[]>([]);

// 表单数据
const formData = ref<RoleApi.Role>();
const isEdit = computed(() => Boolean(formData.value?.id));

// 获取动态标题
const getTitle = computed(() => {
  return isEdit.value ? '编辑角色' : '新增角色';
});

// 创建表单
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useRoleFormSchema(),
  showDefaultActions: false,
});

// 创建抽屉
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    drawerApi.lock();

    try {
      const formValues = await formApi.getValues();

      if (isEdit.value) {
        // 编辑模式
        await updateRole({
          id: formData.value!.id!,
          systemId: formValues.systemId,
          title: formValues.title,
          status: formValues.status,
          remark: formValues.remark,
          handlerName: formValues.handlerName,
          menuIds: formValues.menuIds || [],
        });
        ElMessage.success('编辑成功');
      } else {
        // 新增模式
        await createRole({
          systemId: formValues.systemId,
          title: formValues.title,
          status: formValues.status,
          remark: formValues.remark,
          handlerName: formValues.handlerName,
          menuIds: formValues.menuIds || [],
        });
        ElMessage.success('新增成功');
      }

      await drawerApi.close();
      emit('success');
    } finally {
      drawerApi.unlock();
    }
  },

  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }

    // 确保系统列表已加载
    if (systemList.value.length === 0) {
      await loadSystemList();
    }

    // 加载数据
    const data = drawerApi.getData<RoleApi.Role>();
    formData.value = data;
    if (!data) {
      // 新增模式：无需额外处理，表单schema已包含系统选项
      return;
    }
    drawerApi.lock();
    try {
      if (data.id) {
        // 编辑模式：加载完整角色数据
        const roleData = await getRole(data.id);
        formData.value = roleData;
        await formApi.setValues(roleData);
      }
    } finally {
      drawerApi.unlock();
    }
  },
});

/** 加载系统列表 */
async function loadSystemList() {
  try {
    const { list } = await getSystemList({ pageNum: 1, pageSize: 999 });
    systemList.value = list;

    // 更新表单schema，设置系统选项
    updateFormSchema();
  } catch (error) {
    console.error('加载系统列表失败:', error);
    ElMessage.error('加载系统列表失败');
  }
}

/** 更新表单schema */
function updateFormSchema() {
  const baseSchema = useRoleFormSchema();

  // 动态设置系统选项
  const systemField = baseSchema.find((item) => item.fieldName === 'systemId');
  if (
    systemField &&
    systemField.componentProps &&
    typeof systemField.componentProps === 'object'
  ) {
    const options = systemList.value.map((item) => ({
      label: item.name,
      value: item.id,
    }));
    (systemField.componentProps as any).options = options;
    (systemField.componentProps as any).disabled = isEdit.value;
  }

  // 更新表单schema
  formApi.updateSchema(baseSchema);
}
</script>

<template>
  <Drawer :title="getTitle" width="600px">
    <Form class="mx-4" />
  </Drawer>
</template>
